﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Web;
using System.Runtime.InteropServices;

namespace BlueLotus7.Common
{
    public class WebUtil
    {
        private static WebUtil instance = new WebUtil();
        public static WebUtil Instance
        {
            get
            {
                return instance;
            }
        }
        private WebUtil() { }

        const string zeroCharset = "0";

        [DllImport("Iphlpapi.dll")]
        private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
        [DllImport("Ws2_32.dll")]
        private static extern Int32 inet_addr(string ip);

        /// <summary>
        /// Gets ip and mac address by <c>HttpRequest</c> instance.
        /// </summary>
        /// <param name="httpRequest">The <c>HttpRequest</c> instance.</param>
        /// <param name="ipAddress">The string to set ip address.</param>
        /// <param name="macAddress">The string to set mac address.</param>
        public void GetIpAndMacAddressByHttpRequest(HttpRequest httpRequest, out string ipAddress, out string macAddress)
        {
            ipAddress = string.Empty;
            macAddress = string.Empty;

            if (httpRequest != null)
            {
                ipAddress = GetClientIpByHttpRequest(httpRequest);

                int ipDestination = inet_addr(ipAddress);
                Int64 macinfo = new Int64();
                int len = 6;
                int res = SendARP(ipDestination, 0, ref macinfo, ref len);
                string mac_src = macinfo.ToString("X");
                if (mac_src == zeroCharset)
                {
                    return;
                }

                while (mac_src.Length < 12)
                {
                    mac_src = mac_src.Insert(0, zeroCharset);
                }

                for (int i = 0; i < 11; i++)
                {
                    if (0 == (i % 2))
                    {
                        if (i == 10)
                        {
                            macAddress = macAddress.Insert(0, mac_src.Substring(i, 2));
                        }
                        else
                        {
                            macAddress = "-" + macAddress.Insert(0, mac_src.Substring(i, 2));
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets client ip by <c>HttpRequest</c> instance.
        /// </summary>
        /// <param name="httpRequest">The <c>HttpRequest</c> instance.</param>
        /// <returns>The ip address.</returns>
        public string GetClientIpByHttpRequest(HttpRequest httpRequest)
        {
            string clientIp = string.Empty;

            if (httpRequest != null)
            {
                clientIp = httpRequest.UserHostAddress.ToString().Trim();
            }

            return clientIp;
        }


        /// <summary>
        /// Generates HttpWebRequest by url.
        /// </summary>
        /// <param name="url">The url string.</param>
        /// <returns>The HttpWebRequest instance, or null if fail.</returns>
        public HttpWebRequest GenerateHttpWebRequestByUrl(string url)
        {
            HttpWebRequest httpWebRequest = null;

            try
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                httpWebRequest.Accept = "*";
            }
            catch { }

            return httpWebRequest;
        }

        /// <summary>
        /// Generates HttpWebRequest by uri.
        /// </summary>
        /// <param name="uri">The <c>Uri</c> instance.</param>
        /// <returns>The HttpWebRequest instance, or null if fail.</returns>
        public HttpWebRequest GenerateHttpWebRequestByUri(Uri uri)
        {
            HttpWebRequest httpWebRequest = null;
            try
            {
                httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
                httpWebRequest.Accept = "*";
            }
            catch { }

            return httpWebRequest;
        }

        /// <summary>
        /// Gets text content from WebResponse by defualt encoding.
        /// </summary>
        /// <param name="webResponse">The WebResponse instance.</param>
        /// <returns>The content string.</returns>
        public string ReadTextFromResponse(WebResponse webResponse)
        {
            return ReadTextFromResponse(webResponse, Encoding.Default);
        }

        /// <summary>
        /// Gets text content from WebResponse by specified encoding.
        /// </summary>
        /// <param name="webResponse">The WebResponse instance.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>The content string.</returns>
        public string ReadTextFromResponse(WebResponse webResponse, Encoding encoding)
        {
            string result = string.Empty;

            if (webResponse != null)
            {
                using (Stream responseStream = webResponse.GetResponseStream())
                {
                    if (encoding == null)
                    {
                        encoding = Encoding.UTF8;
                    }
                    StreamReader streamReader = new StreamReader(responseStream, encoding);
                    result = streamReader.ReadToEnd();
                }
            }

            return result;
        }

        /// <summary>
        /// Gets web page by url by default encoding.
        /// </summary>
        /// <param name="url">The url string.</param>
        /// <returns>The content string.</returns>
        public string GetWebPageByUrl(string url)
        {
            return GetWebPageByUrl(url, Encoding.Default);
        }

        /// <summary>
        /// Gets web page by url by specified encoding.
        /// </summary>
        /// <param name="url">The url string.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>The content string.</returns>
        public string GetWebPageByUrl(string url, Encoding encoding)
        {
            string content = string.Empty;

            if (!string.IsNullOrWhiteSpace(url))
            {
                content = GetWebPageByUri(new Uri(url), encoding);
            }

            return content;
        }

        /// <summary>
        /// Gets web page by uri by default encoding.
        /// </summary>
        /// <param name="uri">The uri.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>The content string.</returns>
        public string GetWebPageByUri(Uri uri, Encoding encoding)
        {
            string content = string.Empty;

            if (uri != null)
            {
                HttpWebRequest httpWebRequest = GenerateHttpWebRequestByUri(uri);
                if (httpWebRequest != null)
                {
                    WebResponse response = null;

                    try
                    {
                        response = httpWebRequest.GetResponse();
                        content = ReadTextFromResponse(response, encoding);
                    }
                    finally
                    {
                        if (response != null)
                        {
                            response.Close();
                        }
                    }
                }
            }
            return content;
        }

        /// <summary>
        /// Gets web page by uri by specified encoding.
        /// </summary>
        /// <param name="uri">The uri.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns>The content string.</returns>
        public string GetWebPageByUri(Uri uri)
        {
            return GetWebPageByUri(uri, Encoding.Default);
        }

        /// <summary>
        /// Fills post data on HttpWebRequest.
        /// </summary>
        /// <param name="httpWebRequest">The HttpWebRequest instance.</param>
        /// <param name="dataMappings">The datas.</param>
        public void FillPostDataOnHttpWebRequest(HttpWebRequest httpWebRequest, Dictionary<string, string> dataMappings)
        {
            if (httpWebRequest != null)
            {
                StringBuilder sb = new StringBuilder();
                if (dataMappings != null)
                {
                    foreach (string key in dataMappings.Keys)
                    {
                        string value = string.Empty;
                        if (dataMappings[key] != null)
                        {
                            value = dataMappings[key];
                        }
                        sb.Append(key + "=" + value.Trim() + "&");
                    }

                }
                if (sb.Length > 0)
                {
                    sb.Remove(sb.Length - 1, 1);
                }
                ASCIIEncoding encoding = new ASCIIEncoding();
                byte[] data = encoding.GetBytes(sb.ToString());

                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = data.Length;
                Stream stream = httpWebRequest.GetRequestStream();
                stream.Write(data, 0, data.Length);
                stream.Close();
            }
        }

        /// <summary>
        /// Supply binary download via HttpResponse
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="physicalPath"></param>
        /// <param name="originalFullFileName"></param>
        public void SupplyBinaryDownload(HttpResponse response, string physicalPath, string originalFullFileName)
        {
            if (response != null && !string.IsNullOrWhiteSpace(physicalPath) && File.Exists(physicalPath))
            {
                if (string.IsNullOrWhiteSpace(originalFullFileName))
                {
                    originalFullFileName = "download";
                }
                FileStream fs = new FileStream(physicalPath, FileMode.Open);
                try
                {
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    fs.Dispose();
                    response.ContentType = "application/octet-stream";
                    response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(originalFullFileName, System.Text.Encoding.UTF8));
                    response.BinaryWrite(bytes);
                    response.Flush();
                }
                catch
                {
                    fs.Close();
                    fs.Dispose();
                    throw;
                }
                finally
                {
                    fs.Close();
                    fs.Dispose();
                    response.End();
                }
            }
        }

        /// <summary>
        /// Supply binary download via HttpResponse
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="physicalPath"></param>
        /// <param name="originalFullFileName"></param>
        public void SupplyBinaryDownload(HttpContext context, string physicalPath, string originalFullFileName)
        {
            if (context != null)
            {
                SupplyBinaryDownload(context.Response, physicalPath, originalFullFileName);
            }
        }

        #region Private Method

        private Stream GetStreamFromWebResponse(WebResponse webResponse)
        {
            Stream stream = null;
            if (webResponse != null)
            {
                stream = webResponse.GetResponseStream();
            }
            return stream;
        }

        private bool GetMimeByContentType(string contentType, out string mimeClass, out string mimeType)
        {
            mimeClass = null;
            mimeType = null;
            bool result = false;

            if (!string.IsNullOrWhiteSpace(contentType))
            {
                int index = contentType.IndexOf('/');
                if (index > 0 && index < contentType.Length - 1)
                {
                    mimeClass = contentType.Substring(0, index);
                    mimeType = contentType.Substring(index + 1);
                    result = true;
                }
            }
            return result;
        }

        #endregion

    }
}
